import { defineStore } from 'pinia'
import axios from 'axios'

export const useUserStore = defineStore('user', {
    state: () => ({
        id: '',
        username: '',
        photo: '',
        token: '',
        is_login: false,
        pulling_info: true,
    }),

    actions: {
       updateUser(user) {
            this.id = user.id
            this.username = user.username
            this.photo = user.photo
            this.is_login = user.is_login
        },
        updateToken(token) {
            this.token = token
        },
        updatePullingInfo(pulling_info) {
            this.pulling_info = pulling_info
        },
        logout() {
            this.id = ''
            this.username = ''
            this.photo = ''
       },
       async login(data) {
            try {
                const resp = await axios.post(
                    'http://127.0.0.1:3000/user/account/token/',
                    {
                        username: data.username,
                        password: data.password,
                    }
                )
                if (resp.data.code === 1) {
                    localStorage.setItem('jwtToken', resp.data.data.jwtToken)
                    this.updateToken(resp.data.data.jwtToken)
                    data.success()
                } else {
                    data.error(resp.data)
                }
            } catch (error) {
                data.error(error.response?.data || error)
            }
        },

        async getinfo(data) {
            axios
                .get('http://127.0.0.1:3000/user/account/getInfo/', {
                    headers: {
                        Authorization: 'Bearer ' + this.token,
                    },
                })
                .then((resp) => {
                    if (resp.data.code === 1) {
                        this.updateUser({
                            ...resp.data.data,
                            is_login: true,
                        })
                        data.success()
                    }
                })
                .catch((resp) => {
                    data.error(resp.data)
                    console.log(resp.data)
                })
        },
       fullLogout() {
            localStorage.removeItem('jwtToken')
            this.logout()
        },
          
    }
})
